package com.atguigu.realtime.app.dwm;

import com.alibaba.fastjson.JSON;
import com.atguigu.realtime.app.BaseApp2;
import com.atguigu.realtime.bean.OrderWide;
import com.atguigu.realtime.bean.PaymentInfo;
import com.atguigu.realtime.bean.PaymentWide;
import com.atguigu.realtime.common.Constant;
import com.atguigu.realtime.util.CommonUtil;
import com.atguigu.realtime.util.FlinkSinkUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.co.ProcessJoinFunction;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.util.Collector;

import java.time.Duration;
import java.util.Map;

import static com.atguigu.realtime.common.Constant.*;

/**
 * Created by RUI on 2021/6/30 9:13
 */
public class DwmPaymentWideApp extends BaseApp2 {

    public static void main(String[] args) {
        new DwmPaymentWideApp().init(3004, 1, "DwmPaymentWideApp", "DwmPaymentWideApp",
            TOPIC_DWD_PAYMENT_INFO, TOPIC_DWM_ORDER_WIDE);
    }

    @Override
    public void run(StreamExecutionEnvironment env, Map<String, DataStreamSource<String>> mapStream) {
        KeyedStream<PaymentInfo, Long> payKeyedStream = mapStream.get(TOPIC_DWD_PAYMENT_INFO)
            .map(jsonStr -> JSON.parseObject(jsonStr, PaymentInfo.class))
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<PaymentInfo>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                    .withTimestampAssigner((pay, ts) -> CommonUtil.toTs(pay.getCreate_time()))
            )
            .keyBy(PaymentInfo::getOrder_id);
        KeyedStream<OrderWide, Long> orderWideKeyedStream = mapStream.get(TOPIC_DWM_ORDER_WIDE)
            .map(jsonStr -> JSON.parseObject(jsonStr, OrderWide.class))
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<OrderWide>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                    .withTimestampAssigner((pay, ts) -> CommonUtil.toTs(pay.getCreate_time()))
            )
            .keyBy(OrderWide::getOrder_id);

        // 对这两个流做interval join
        payKeyedStream.intervalJoin(orderWideKeyedStream)
            .between(Time.minutes(-30),Time.seconds(3))
            .process(new ProcessJoinFunction<PaymentInfo, OrderWide, PaymentWide>() {
                @Override
                public void processElement(PaymentInfo left, OrderWide right, Context ctx, Collector<PaymentWide> out) throws Exception {
                    out.collect(new PaymentWide(left,right));
                }
            })
            .map(JSON::toJSONString)
            .addSink(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWM_PAYMENT_WIDE));

    }
}
